<template>
  <div class="page-container">
    <div class="nav-bar">
      <van-nav-bar
        title="发布苗木"
        left-arrow
        @click-left="onClickLeft"
        fixed
        placeholder
        safe-area-inset-top
      ></van-nav-bar>
    </div>
    <div class="content">
      <!-- 商品图片上传 -->
      <div class="upload-section">
        <div class="section-title"><span class="required">*</span>商品主图</div>
        <div class="upload-content">
          <div class="upload-media-wrapper">
            <van-uploader
              v-model="images"
              :max-count="4"
              :after-read="afterRead"
              :upload-icon="pic"
              :multiple="true"
              @delete="deleteOssIds"
            />
            <!-- <van-uploader
              v-model="formData.images"
              :max-count="2"
              :after-read="afterRead"
              :upload-icon="video"
            >
              <template #preview-cover="{ file }">
                <div class="preview-cover">
                  <van-icon name="cross" @click.stop="removeFile(file)" />
                </div>
              </template>
</van-uploader> -->
          </div>

          <div class="upload-tips">
            <p class="tips1">上传照片4个+视频1个，总共可获得7分</p>
            <p class="tips2">
              <span>请上传清晰无任何水印涂鸦的照片以及15秒内视频</span>
              <!-- <span class="check-example">查看示例<van-icon name="arrow" /></span> -->
            </p>
          </div>
        </div>
      </div>

      <div class="spe-section">
        <div class="spe-item" @click="shwoMpPicker = true">
          <div class="item-left">
            <span class="require">*</span
            ><span>{{ formData.userNurseryId ? formData.userNurseryName : '选择苗圃' }}</span>
          </div>
          <div class="item-right"><span>请选择</span><van-icon name="arrow" /></div>
        </div>
        <div class="spe-item" @click="showMmPicker = true">
          <div class="item-left">
            <span class="require">*</span
            ><span>{{ formData.baseProductId ? formData.baseProductName : '选择苗木' }}</span>
          </div>
          <div class="item-right"><span>请选择</span><van-icon name="arrow" /></div>
        </div>
        <div class="spe-item" @click="handleAttribute">
          <div class="item-left"><span class="require">*</span><span>形态、规格、类型</span></div>
          <div class="item-right"><span>请选择</span><van-icon name="arrow" /></div>
        </div>

        <!-- 规格信息 -->
        <div v-if="showSpeInfo" class="spe-info">
          <div class="spe-info-item">
            <div class="left">形态:</div>
            <div class="center">{{ formData.categoryName }}</div>
            <div class="right"></div>
          </div>
          <div class="spe-info-item" v-for="item in formData.attributes">
            <div class="left">{{ item.attributeName }}:</div>
            <div class="center">{{ item.minValue }}-{{ item.maxValue }}</div>
            <div class="right">{{ item.unit }}</div>
          </div>
        </div>

        <div class="spe-tips-croci">填写每个参数+0.5分</div>
        <div class="spe-tips-grey">苗木规格与详细越快被搜索</div>
        <div class="spe-item spe">
          <div class="item-left"><span class="require">*</span><span>价格</span></div>
          <div class="item-right">
            <van-field
              type="number"
              input-align="center"
              v-model="formData.priceMin"
              placeholder="库存"
            />-<van-field
              type="number"
              input-align="center"
              v-model="formData.priceMax"
              placeholder="最大面值"
            />元

            <van-checkbox class="item-status" v-model="priceType">面议</van-checkbox>
          </div>
        </div>
        <div class="spe-item spe">
          <div class="item-left"><span class="require">*</span><span>库存</span></div>
          <div class="item-right">
            <van-field
              type="number"
              input-align="center"
              v-model="formData.pushNum"
              placeholder="请输入库存"
            />株
          </div>
        </div>
        <div class="spe-tips-croci">填写价格+1分</div>
      </div>

      <div class="spe-section">
        <van-field
          v-model="formData.productNo"
          label="苗木编号（选填）"
          placeholder="请输入"
          input-align="right"
        />
        <van-field
          v-model="formData.remark"
          label="备注"
          placeholder="请输入内容"
          input-align="right"
        />
        <van-field name="switch" label="开关" input-align="right">
          <template #input>
            <van-switch
              v-model="formData.isOpen"
              :active-value="'1'"
              :inactive-value="'0'"
              size="22px"
            />
          </template>
        </van-field>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-btn" :class="deviceType === 'ios' ? 'safe-area' : ''">
      <van-button type="primary" block @click="onSubmit">确认发布</van-button>
    </div>

    <!-- 苗圃选择弹窗 -->
    <van-popup
      v-model:show="shwoMpPicker"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <mpInfo v-model:show="shwoMpPicker" @select="selectMp"></mpInfo>
    </van-popup>

    <!-- 选择苗木弹窗 -->
    <van-popup
      v-model:show="showMmPicker"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <mmPicker v-model:show="showMmPicker" @select="onMmSelect"></mmPicker>
    </van-popup>

    <!-- 规格选择弹窗 -->
    <van-popup
      v-model:show="showSpePicker"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <spePicker
        v-model:show="showSpePicker"
        :baseProductId="formData.baseProductId"
        @select="onSpeSelect"
      ></spePicker>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { getDeviceType } from '@/utils/tools'
import bridge from '@/utils/bridge'
import { ref, reactive } from 'vue'
import { showToast } from 'vant'
import mpInfo from './components/mpInfo.vue'
import mmPicker from './components/mmPicker.vue'
import spePicker from './components/spePicker.vue'
import pic from '../assets/pic.png'
import { pushProductAdd, upload } from '@/api'

interface FormData {
  ossId: string
  userNurseryId: string
  userNurseryName: string
  baseProductId: string
  baseProductName: string
  attributes: []
  plantAttributeId: string
  plantAttributeName: string
  priceMin: string
  priceMax: string
  productNo: string
  remark: string
  isOpen: string
  userId: string
  categoryId: string
  categoryName: string
  pushNum: string
  priceType: string
}

const formData = reactive<FormData>({
  ossId: '',
  userNurseryId: '',
  userNurseryName: '',
  baseProductId: '',
  baseProductName: '',
  attributes: [],
  plantAttributeId: '',
  plantAttributeName: '',
  priceMin: '',
  priceMax: '',
  productNo: '',
  remark: '',
  isOpen: '1',
  userId: '',
  categoryId: '',
  categoryName: '',
  pushNum: '',
  priceType: ''
})
const images = ref([])
// 苗圃弹窗控制
const shwoMpPicker = ref(false)
// 苗木弹窗控制
const showMmPicker = ref(false)
// 规格弹窗控制
const showSpePicker = ref(false)
// 规格信息
const showSpeInfo = ref(false)
// 是否面议
const priceType = ref(false)
// 终端类型
const deviceType = ref('')

// 图片上传
const afterRead = async (file: any) => {
  let data = new FormData()
  if (file.file) {
    file.status = 'uploading'
    file.message = '上传中...'
    data.append('files', file.file)
  } else {
    file.map((item: any) => {
      item.status = 'uploading'
      item.message = '上传中...'
      data.append('files', item.file)
    })
  }
  let res = await upload(data)
  if (res.code === 200) {
    if (file.file) {
      file.status = 'done'
      file.message = '上传成功'
    } else {
      file.map((item: any) => {
        item.status = 'done'
        item.message = '上传成功'
      })
    }
    res.data.map((item: any) => {
      if (formData.ossId) {
        formData.ossId = `${formData.ossId},${item.ossId}`
      } else {
        formData.ossId = `${item.ossId}`
      }
    })
  }
}

// 删除图片
const deleteOssIds = (file: any, detail: any) => {
  let arr = formData.ossId.split(',')
  arr.splice(detail.index, 1)
  formData.ossId = arr.join(',')
}

// 苗圃选择回调
const selectMp = (data: any) => {
  formData.userNurseryId = data.userNurseryId
  formData.userNurseryName = data.nurseryName
}

// 选择苗木回调
const onMmSelect = (data: any, index: number) => {
  showMmPicker.value = false
  showSpeInfo.value = false
  formData.baseProductId = data.baseProductId
  formData.baseProductName = data.productName
  formData.attributes = []
  formData.plantAttributeId = ''
  formData.plantAttributeName = ''
  formData.categoryId = ''
  formData.categoryName = ''
}

// 选择规格回调
const onSpeSelect = (data: any, plantAttributes: any) => {
  formData.attributes = data.attributes
  formData.categoryId = data.categoryId
  formData.categoryName = data.categoryName
  formData.plantAttributeId = plantAttributes.plantAttributeId
  formData.plantAttributeName = plantAttributes.plantAttributeName
  showSpeInfo.value = true
}

const handleAttribute = () => {
  if (formData.baseProductId) {
    showSpePicker.value = true
  } else {
    showToast('请先选择苗木')
  }
}

// 提交表单
const onSubmit = async () => {
  let valid = true
  // 表单验证
  if (!formData.ossId) {
    showToast('请上传商品主图')
    valid = false
    return
  }
  if (!formData.userNurseryId) {
    showToast('请选择苗圃')
    valid = false
    return
  }
  if (!formData.baseProductId) {
    showToast('请选择苗木')
    valid = false
    return
  }
  if (formData.attributes.length === 0) {
    showToast('请选择规格')
    valid = false
    return
  }
  if (priceType.value) {
    formData.priceType = '1'
  } else {
    formData.priceType = '2'
    if (!formData.priceMin || !formData.priceMax) {
      showToast('请填写价格区间')
      valid = false
      return
    }
  }

  if (!formData.pushNum || formData.pushNum == 0) {
    showToast('请填写库存')
    valid = false
    return
  }

  if (valid) {
    let res = await pushProductAdd(formData)
    showToast(res.msg)
    navigateBackTo()
  }
}

// 跳转到首页
const navigateBackTo = () => {
  bridge.navigateBackTo({
    value: 'home'
  })
}

const onClickLeft = () => {
  bridge.closeWebView()
}

onMounted(async () => {
  bridge.setNavigationBarVisible({
    value: '0'
  })
  deviceType.value = getDeviceType()
})
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;

  :deep(.nav-bar) {
    .van-nav-bar__arrow {
      color: #222;
      font-size: 17px;
    }

    .van-nav-bar__title {
      font-size: 17px;
      font-weight: normal;
      color: #222;
    }
  }

  .content {
    flex: 1;
    overflow-y: auto;
    .upload-section {
      background: #fff;
      padding: 16px 12px;
      margin-bottom: 10px;

      .section-title {
        margin-bottom: 10px;
        font-size: 15px;
        color: #222;

        .required {
          color: #ff0000;
          margin-right: 4px;
        }
      }

      .upload-content {
        .upload-tips {
          font-size: 11px;
          color: #999;
          line-height: 15px;

          .tips1 {
            font-size: 11px;
            color: #f1641a;
          }

          .tips2 {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .check-example {
              font-size: 12px;
              color: #32bc05;
            }
          }

          p {
            margin: 0;
            line-height: 1.5;
          }

          .check-example {
            color: #32bc05;
          }
        }
      }

      :deep(.van-icon__image) {
        width: 100%;
        height: 100%;
      }

      :deep(.van-uploader__upload) {
        width: 74px;
        height: 74px;
      }

      :deep(.van-image) {
        width: 74px;
        height: 74px;
      }

      :deep(.van-uploader) {
        .van-uploader__upload {
          width: 74px;
          height: 74px;
          margin-right: 8px;
          background-color: #fff;
        }

        .van-uploader__preview {
          margin-right: 8px;
        }

        .preview-cover {
          position: absolute;
          top: 0;
          right: 0;
          padding: 4px;

          .van-icon {
            color: #fff;
            font-size: 18px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 50%;
            padding: 2px;
          }
        }
      }
    }

    .spe-section {
      margin-bottom: 10px;
      padding: 12px;
      background: #fff;

      .spe-item {
        padding: 16px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .item-left {
          font-size: 15px;
          color: #222;

          .require {
            margin-right: 3px;
            color: #ff0000;
          }
        }

        .item-right {
          color: #999;
          font-size: 14px;
        }

        &.spe {
          justify-content: left;
          gap: 16px;

          .item-right {
            display: flex;
            align-items: center;
            gap: 3px;
            color: #999;

            .van-cell {
              padding: 0;
              width: 80px;
              height: 28px;
              line-height: 28px;
              text-align: center;
              background: #fff;
              border: 1px solid #ddd;
              border-radius: 2px;
              font-size: 12px;
            }
          }
        }
      }

      .spe-tips-croci {
        margin-bottom: 7px;
        line-height: 15px;
        color: #f1641a;
        font-size: 11px;
      }

      .spe-tips-grey {
        line-height: 17px;
        color: #999;
        font-size: 12px;
      }

      .van-cell {
        padding: 0;
        font-size: 14px;
        height: 50px;

        :deep(.van-field__label) {
          flex: 1;
          font-size: 15px;
          color: #222;
        }
      }

      .van-cell:after {
        border: none;
      }

      :deep(.van-field__control) {
        color: #999;
      }

      :deep(.van-switch--on) {
        background: #32bc05;
      }

      .spe-info {
        padding: 5px 30px;

        .spe-info-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          line-height: 30px;
          font-size: 14px;
          color: #222;

          .left {
            color: #999;
            flex: 0 0 30%;
          }

          .center {
            flex: 1;
            text-align: center;
          }

          .right {
            flex: 0 0 10%;
          }
        }
      }
    }
  }

  .submit-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 0;
    padding: 13px 16px;
    background: #fff;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
    z-index: 99;

    :deep(.van-button) {
      height: 45px;
      line-height: 45px;
      border-radius: 22px;
      font-size: 16px;
      background: #32bc05;
      border-color: #32bc05;
    }
  }
}

:deep(input.van-field__control::-webkit-input-placeholder) {
  color: #999;
}
</style>
